<template>
  <div class="wash-statistics">
    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ overviewData.totalOrders }}</div>
            <div class="stat-label">总订单数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">¥{{ overviewData.totalRevenue }}</div>
            <div class="stat-label">总营收</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ overviewData.totalCustomers }}</div>
            <div class="stat-label">客户总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ overviewData.avgSatisfaction }}</div>
            <div class="stat-label">平均满意度</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>月度营收趋势</span>
          </template>
          <div ref="revenueChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>服务类型分布</span>
          </template>
          <div ref="serviceChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>设备利用率</span>
          </template>
          <div ref="equipmentChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { statistics } from '@/api/wash/index'

// 概览数据
const overviewData = reactive({
  totalOrders: 0,
  totalRevenue: 0,
  totalCustomers: 0,
  avgSatisfaction: 0
})

// 图表引用
const revenueChart = ref(null)
const serviceChart = ref(null)
const equipmentChart = ref(null)

let revenueChartInstance = null
let serviceChartInstance = null
let equipmentChartInstance = null

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const res = await getWashStatistics()
    if (res && (res.code === 200 || res.data)) {
      const data = res.data || res
      Object.assign(overviewData, {
        totalOrders: data.totalOrders || 0,
        totalRevenue: data.totalRevenue || 0,
        totalCustomers: data.totalCustomers || 0,
        avgSatisfaction: data.avgSatisfaction || 0
      })
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.warning('获取统计数据失败，请检查网络连接')
  }
}

// 初始化营收趋势图表
const initRevenueChart = async () => {
  if (!revenueChart.value) return
  
  revenueChartInstance = echarts.init(revenueChart.value)
  
  try {
    const res = await getWashRevenueChart({ period: 'monthly' })
    const chartData = res.data || res
    
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: chartData.dates || []
      },
      yAxis: {
        type: 'value',
        name: '营收（元）'
      },
      series: [{
        name: '月度营收',
        type: 'line',
        data: chartData.values || [],
        smooth: true,
        itemStyle: {
          color: '#409eff'
        }
      }]
    }
    revenueChartInstance.setOption(option)
  } catch (error) {
    console.error('获取营收图表数据失败:', error)
    // 显示空图表
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value',
        name: '营收（元）'
      },
      series: [{
        name: '月度营收',
        type: 'line',
        data: [],
        smooth: true,
        itemStyle: {
          color: '#409eff'
        }
      }]
    }
    revenueChartInstance.setOption(option)
  }
}

// 初始化服务类型分布图表
const initServiceChart = async () => {
  if (!serviceChart.value) return
  
  serviceChartInstance = echarts.init(serviceChart.value)
  
  try {
    const res = await getWashServiceChart({ period: 'monthly' })
    const chartData = res.data || res
    
    const option = {
      tooltip: {
        trigger: 'item'
      },
      series: [{
        name: '服务类型',
        type: 'pie',
        radius: '70%',
        data: (chartData.labels || []).map((label, index) => ({
          name: label,
          value: (chartData.values || [])[index] || 0
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    serviceChartInstance.setOption(option)
  } catch (error) {
    console.error('获取服务类型图表数据失败:', error)
    // 显示空图表
    const option = {
      tooltip: {
        trigger: 'item'
      },
      series: [{
        name: '服务类型',
        type: 'pie',
        radius: '70%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    serviceChartInstance.setOption(option)
  }
}

// 初始化设备利用率图表
const initEquipmentChart = async () => {
  if (!equipmentChart.value) return
  
  equipmentChartInstance = echarts.init(equipmentChart.value)
  
  try {
    const res = await getWashEquipmentChart({ period: 'monthly' })
    const chartData = res.data || res
    
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: chartData.legend || []
      },
      xAxis: {
        type: 'category',
        data: chartData.xAxis || []
      },
      yAxis: {
        type: 'value',
        name: '利用率（%）',
        max: 100
      },
      series: chartData.series || []
    }
    equipmentChartInstance.setOption(option)
  } catch (error) {
    console.error('获取设备利用率图表数据失败:', error)
    // 显示空图表
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: []
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value',
        name: '利用率（%）',
        max: 100
      },
      series: []
    }
    equipmentChartInstance.setOption(option)
  }
}

// 生命周期
onMounted(async () => {
  await getStatisticsData()
  
  nextTick(() => {
    initRevenueChart()
    initServiceChart()
    initEquipmentChart()
  })
})
</script>

<style lang="scss" scoped>
.wash-statistics {
  padding: 20px;
  
  .stats-overview {
    margin-bottom: 20px;
    
    .stat-card {
      text-align: center;
      
      .stat-content {
        .stat-number {
          font-size: 28px;
          font-weight: bold;
          color: #409eff;
          margin-bottom: 10px;
        }
        
        .stat-label {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
  
  .charts-row {
    margin-bottom: 20px;
    
    .chart-container {
      height: 300px;
    }
  }
}
</style> 